package cn.com.ieds.dao;

import cn.com.ieds.util.DbUtil;
import net.sf.json.JSONArray;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PermissionsDao {
    private Connection connection;
    private PreparedStatement preparedStatement;
    private ResultSet rs;
    private String sql;

    // 获取全部权限 [{permissions_id,permissions_name,permissions_type,permissions_router,
    // children:[{permissions_id,permissions_name,permissions_type,permissions_router},...]},{},...]
    public void getPermissions(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        connection = DbUtil.getInstace().getConnection();
        ResultSet innerRs;
        sql = "select permissions_id,permissions_name,permissions_type,permissions_router from tbl_permissions where permissions_parentid = 0";
        try {
            preparedStatement = connection.prepareStatement(sql);
            rs = preparedStatement.executeQuery();
            List<Object> permissions = new ArrayList<>();
            Map<String, Object> parentPermission;
            List<Object> childPermissions;
            Map<String, Object> childPermission;
            while (rs.next()) {
                parentPermission = new HashMap<>();
                parentPermission.put("permissions_id", rs.getInt("permissions_id"));
                parentPermission.put("permissions_name", rs.getString("permissions_name"));
                parentPermission.put("permissions_type",rs.getString("permissions_type"));
                parentPermission.put("permissions_router",rs.getString("permissions_router"));
                childPermissions = new ArrayList<>();
                sql = "select permissions_id,permissions_name,permissions_type,permissions_router from tbl_permissions where permissions_parentid = "
                        + rs.getInt("permissions_id");
                preparedStatement = connection.prepareStatement(sql);
                innerRs = preparedStatement.executeQuery();
                while (innerRs.next()) {
                    childPermission = new HashMap<>();
                    childPermission.put("permissions_id", innerRs.getInt("permissions_id"));
                    childPermission.put("permissions_name", innerRs.getString("permissions_name"));
                    childPermission.put("permissions_type",innerRs.getString("permissions_type"));
                    childPermission.put("permissions_router",innerRs.getString("permissions_router"));
                    childPermissions.add(childPermission);
                }
                parentPermission.put("children", childPermissions);
                permissions.add(parentPermission);
            }
            response.getWriter().write(JSONArray.fromObject(permissions).toString());
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }  finally {
            connection.close();
        }
    }

    // 根据角色获取对应的权限列表，作为v-permissions参数使用 [permissions_name,...]
    public void getPermissionsListByRole(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        connection = DbUtil.getInstace().getConnection();
        int roleId = Integer.parseInt(request.getParameter("role_id"));
        sql = "select permissions_name from tbl_permissions,role_re_permissions " +
                "where role_re_permissions.role_id = ? and tbl_permissions.permissions_id = role_re_permissions.permissions_id";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,roleId);
            rs = preparedStatement.executeQuery();
            List<String> permissionsName = new ArrayList<>();
            while (rs.next()) {
                permissionsName.add(rs.getString("permissions_name"));
            }
            response.getWriter().write(permissionsName.toString());
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }
    }

    // 根据角色获取对应的权限，用作展示[{permissions_name,permissions_parentid,permissions_router},...]
    public void getPermissionsByRole(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        connection = DbUtil.getInstace().getConnection();
        int roleId = Integer.parseInt(request.getParameter("role_id"));
        sql = "select permissions_name,permissions_parentid,permissions_router from tbl_permissions,role_re_permissions " +
                "where role_re_permissions.role_id = ? and tbl_permissions.permissions_id = role_re_permissions.permissions_id";
        List<Object> json = new ArrayList<>();
        Map<String, Object> info;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,roleId);
            rs = preparedStatement.executeQuery();
            while (rs.next()) {
                info = new HashMap<>();
                info.put("permissions_name",rs.getString("permissions_name"));
                info.put("permissions_parentid",rs.getInt("permissions_parentid"));
                info.put("permissions_router",rs.getString("permissions_router"));
                json.add(info);
            }
            response.getWriter().write(JSONArray.fromObject(json).toString());
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }
    }

    //获取当前角色侧边栏可以渲染的权限列表及跳转链接
    public void getPermissionsListAndRouter(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        connection = DbUtil.getInstace().getConnection();
        int roleId = Integer.parseInt(request.getParameter("role_id"));
        sql = "select permissions_name,permissions_router from tbl_permissions,role_re_permissions " +
                "where role_re_permissions.role_id = ? " +
                "and tbl_permissions.permissions_id = role_re_permissions.permissions_id " +
                "and tbl_permissions.permissions_type = 'list'";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,roleId);
            rs = preparedStatement.executeQuery();
            List<Object> json = new ArrayList<>();
            Map<String,Object> permission;
            while (rs.next()) {
                permission = new HashMap<>();
                permission.put("permissions_name",rs.getString("permissions_name"));
                permission.put("permissions_router",rs.getString("permissions_router"));
                json.add(permission);
            }
            response.getWriter().write(JSONArray.fromObject(json).toString());
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }
    }

    // 添加权限
    public void addPermissions(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        connection = DbUtil.getInstace().getConnection();
        String name = request.getParameter("name");
        String type = request.getParameter("type");
        String router = request.getParameter("router");
        Integer parentId;
        if("list".equals(type)){
            parentId = 0;
        }else{
            parentId = Integer.parseInt(request.getParameter("parentId"));
        }
        sql = "insert into tbl_permissions values(null,?,?,?,?)";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,name);
            preparedStatement.setInt(2,parentId);
            preparedStatement.setString(3,type);
            preparedStatement.setString(4,router);
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }
    }

    //删除权限
    public void delPermissions(HttpServletRequest request, HttpServletResponse response) {
        connection = DbUtil.getInstace().getConnection();
        int permissionsId = Integer.parseInt(request.getParameter("permissions_id"));
        try {
            connection.setAutoCommit(false);
            sql = "delete from tbl_permissions where permissions_id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,permissionsId);
            preparedStatement.execute();

            sql = "select permissions_parentid from tbl_permissions where permissions_id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,permissionsId);
            rs = preparedStatement.executeQuery();
            if(rs.next()){
                if(0==rs.getInt("permissions_parentid")){
                    sql = "delete from tbl_permissions where permissions_parentid = ?";
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setInt(1,permissionsId);
                    preparedStatement.execute();
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}
